﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Text.RegularExpressions;
using PrgsMgr;
using DalMgr;
namespace DataHandle
{
    public class DataExport
    {
        private string[] arrTitle = new string[] { "姓名", "二级采销部门", "三级采销部门", "暂停天数", "暂停时长分段" };
        private string dstFileName;
        private const string SFT_CFG_DST_FILE_NAME = "DST_FILE";
        private const int PRGS_ID = 0;
        
        Connection con;
        public DataExport()
        {
            dstFileName = SftDataMgr.ReadStr(PubVal.SFT_CFG, SFT_CFG_DST_FILE_NAME, "结果");
        }
        public void Import(object filePath)
        {
            
            ProgressManager.Init(PRGS_ID, "", 1);
            ProgressManager.UpdateVale(PRGS_ID,"新建结果工作簿");
            string dstPath = filePath.ToString().Replace(Path.GetFileName(filePath.ToString()), dstFileName+DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx");
            con = new Connection();
            con.InitDic();
            IWorkbook wkBk = new XSSFWorkbook();
            ISheet wkShtSrc = wkBk.CreateSheet("单品详情");

            Handle_ProductDetail(wkBk, wkShtSrc, filePath.ToString());
            Handle_Sheet(wkBk, wkShtSrc, "订单去重",new int[]{0,5,32,33,34,35});
            Handle_Sheet(wkBk, wkShtSrc, "暂停原因", new int[] { 0, 5, 9, 10, 11, 34, 35 });
            Handle_Sheet(wkBk, wkShtSrc, "采购员详情", new int[] { 0, 5, 31, 33, 34, 35 });
            Handle_Sheet(wkBk, wkShtSrc, "品牌详情", new int[] { 0, 5, 20, 34, 35 });
            Handle_NotSheet(wkBk, wkShtSrc, "非现货暂停原因", new int[] { 0, 5, 9, 10, 11, 19, 20, 32, 33, 34, 35 });

            ProgressManager.UpdateVale(PRGS_ID, "正在保存结果");
            FileStream FS = File.Create(dstPath);
            wkBk.Write(FS);
            wkBk.Close();
            FS.Close();
            ProgressManager.CloseProcessFrm();
        }
        private string GetDaysStr(int days)
        {
            if (days <= 4)
            {
                return "4天内";
            }
            else if (days < 8)
            {
                return "4-7天";
            }
            else if (days < 31)
            {
                return "7-30天";
            }
            else
            {
                return "30天以上";
            }

        }

        private void Handle_ProductDetail(IWorkbook wkBk,ISheet wkSht,string filePath)
        {

            using (FileStream FS = new FileStream(filePath.ToString(), FileMode.OpenOrCreate, FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(FS, Encoding.Default))
                {
                    string str, strName;
                    string[] arr;
                    int curRow = 0;
                    long filePos = 0;
                    ProgressManager.Init(PRGS_ID, string.Format("正在处理【{0}】", "匹配数据"), FS.Length);
                    while (null != (str = sr.ReadLine()))
                    {
                        ProgressManager.UpdateVale(PRGS_ID, sr.BaseStream.Position - filePos);
                        filePos = sr.BaseStream.Position;
                        arr = str.Split(',');
                        if (arr.Length != 32)
                        {
                            continue;
                        }

                        strName = arr[18];
                        if (curRow == 0)
                        {
                            IRow row = wkSht.CreateRow(curRow);
                            ICell cell = row.CreateCell(0);
                            cell.SetCellValue("日期");
                            for (int i = 0; i < arr.Length - 2; i++)
                            {
                                cell = row.CreateCell(row.Cells.Count);
                                cell.SetCellValue(arr[i]);
                            }
                            for (int i = 0; i < arrTitle.Length; i++)
                            {
                                cell = row.CreateCell(row.Cells.Count);
                                cell.SetCellValue(arrTitle[i]);
                            }
                            curRow++;
                        }
                        if (con.ItemExsit(strName))
                        {
                            ItemInfo info = con.GetItem(strName);
                            IRow row = wkSht.CreateRow(curRow);
                            ICell cell = row.CreateCell(row.Cells.Count);
                            cell.SetCellValue(DateTime.Today.ToString("yyyy-MM-dd"));
                            for (int i = 0; i < arr.Length - 2; i++)
                            {
                                cell = row.CreateCell(row.Cells.Count);
                                cell.SetCellValue(arr[i]);
                            }
                            cell = row.CreateCell(row.Cells.Count);
                            cell.SetCellValue(info.Name);
                            cell = row.CreateCell(row.Cells.Count);
                            cell.SetCellValue(info.Department2);
                            cell = row.CreateCell(row.Cells.Count);
                            cell.SetCellValue(info.Department3);
                            int days = (DateTime.Today - Convert.ToDateTime(arr[12])).Days;
                            cell = row.CreateCell(row.Cells.Count);
                            cell.SetCellValue(days);
                            cell = row.CreateCell(row.LastCellNum);
                            cell.SetCellValue(GetDaysStr(days));
                            curRow++;
                        }
                        
                    }
                    sr.Close();
                    FS.Close();
                }
            }
        }

        private void Handle_Sheet(IWorkbook wkBk, ISheet wkShtSrc, string shtName, int[] arrCol)
        {
            Dictionary<string, string> dicOrder = new Dictionary<string, string>();
            ISheet wkSht = wkBk.CreateSheet(shtName);
            int rowIdx, curRow = 0 ;
            string str;
            IRow srcRow, dstRow;
            ICell dstCell;
            ProgressManager.Init(PRGS_ID, string.Format("正在处理【{0}】",shtName), wkShtSrc.LastRowNum - wkShtSrc.FirstRowNum + 1);
            for (rowIdx = wkShtSrc.FirstRowNum; rowIdx <= wkShtSrc.LastRowNum; rowIdx++)
            {
                ProgressManager.UpdateVale(PRGS_ID);
                srcRow = wkShtSrc.GetRow(rowIdx);
                if (srcRow == null)
                {
                    continue;
                }
                str = "";
                for (int idx = 0; idx < arrCol.Length; idx++)
                {
                    str += srcRow.GetCell(arrCol[idx]).ToString();
                }
                if (dicOrder.ContainsKey(str))
                {
                    continue;
                }
                srcRow = wkShtSrc.GetRow(rowIdx);
                dstRow = wkSht.CreateRow(curRow++);
                for (int idx = 0; idx < arrCol.Length; idx++)
                {
                    dstCell = dstRow.CreateCell(dstRow.Cells.Count);
                    CopyCell(ref dstCell, srcRow.GetCell(arrCol[idx]));
                }
                dicOrder.Add(str, "");
            }
        }
        private void Handle_NotSheet(IWorkbook wkBk, ISheet wkShtSrc, string shtName, int[] arrCol)
        {
            Dictionary<string, string> dicOrder = new Dictionary<string, string>();
            ISheet wkSht = wkBk.CreateSheet(shtName);
            int rowIdx, curRow = 0;
            string str;
            IRow srcRow, dstRow;
            ICell dstCell;
            ProgressManager.Init(PRGS_ID, string.Format("正在处理【{0}】", shtName), wkShtSrc.LastRowNum - wkShtSrc.FirstRowNum + 1);
            for (rowIdx = wkShtSrc.FirstRowNum; rowIdx <= wkShtSrc.LastRowNum; rowIdx++)
            {
                ProgressManager.UpdateVale(PRGS_ID);
                srcRow = wkShtSrc.GetRow(rowIdx);
                if (srcRow == null)
                {
                    continue;
                }
                str = srcRow.GetCell(28).ToString();
                if (str == "现货" || str == "未知库存")
                {
                    continue;
                }
                str = "";
                for (int idx = 0; idx < arrCol.Length; idx++)
                {
                    str += srcRow.GetCell(arrCol[idx]).ToString();
                }
                if (dicOrder.ContainsKey(str))
                {
                    continue;
                }
                srcRow = wkShtSrc.GetRow(rowIdx);
                dstRow = wkSht.CreateRow(curRow++);
                for (int idx = 0; idx < arrCol.Length; idx++)
                {
                    dstCell = dstRow.CreateCell(dstRow.Cells.Count);
                    CopyCell(ref dstCell, srcRow.GetCell(arrCol[idx]));
                }
                dicOrder.Add(str, "");
            }
        }

        private void CopyCell(ref ICell dstCell, ICell srcCell)
        {
            switch (srcCell.CellType)
            {
                case CellType.String:
                    dstCell.SetCellValue(srcCell.StringCellValue);
                    break;
                case CellType.Numeric:
                    dstCell.SetCellValue(srcCell.NumericCellValue);
                    break;
                case CellType.Blank:
                    dstCell.SetCellValue(srcCell.BooleanCellValue);
                    break;
                default:
                    break;
            }
            
            dstCell.CellStyle = srcCell.CellStyle;
        }

    }
}
